﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Common.Logging;
using Spring.Context;
using Spring.Context.Support;

namespace BOSS.Web
{
    /// <summary>
    /// 而在IIS7集成模式下则不允许在Global.asax文件中进行ContextRegistry
    /// </summary>
    public class InitializeModule : Spring.Context.Support.WebSupportModule
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(InitializeModule));
        private static bool isInitialized = false;
        private static object _lock = new object();

        public IList<IGlobalModule> GlobalModules { get; set; }
        public IList<ICustomModelBinder> ModelBinders { get; set; }

        public override void Init(HttpApplication app)
        {
            base.Init(app);
            this.Initialize(app);
        }

        private void Initialize(HttpApplication app)
        {
            if (!isInitialized)
            {
                lock (_lock)
                {
                    if (!isInitialized)
                    {
                        IApplicationContext appContext = ContextRegistry.GetContext();
                        appContext.ConfigureObject(this, "GlobalModuleInitializer");
                        appContext.ConfigureObject(this, "ModelBinderInitializer");

                        if (this.GlobalModules != null)
                        {
                            foreach (IGlobalModule module in this.GlobalModules)
                            {
                                logger.Info("初始化 " + module.Name);
                                try
                                {
                                    module.Initialize(app, appContext);
                                }
                                catch (Exception ex)
                                {
                                    logger.Warn(module.Name + "初始化异常", ex);
                                }
                            }
                        }

                        if (this.ModelBinders != null)
                        {
                            foreach (ICustomModelBinder modelBinder in this.ModelBinders)
                            {
                                foreach (Type type in modelBinder.SupportedTypes)
                                {
                                    logger.Info(string.Concat("注册模型绑定器：", type.Name, " - ", modelBinder.GetType().Name));
                                    System.Web.Mvc.ModelBinders.Binders.Add(type, modelBinder);
                                }
                            }
                        }
                    }
                    isInitialized = true;
                }
            }
        }
    }
}
